<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍管理 - 商家端</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
            font-family: 'Roboto', sans-serif;
            min-height: 100vh;
            margin: 0;
        }
        .layout {
            display: flex;
            min-height: 100vh;
        }
        .sidebar {
            width: 210px;
            background: #fff;
            box-shadow: 2px 0 16px rgba(0,0,0,0.07);
            display: flex;
            flex-direction: column;
            padding: 32px 0 0 0;
        }
        .sidebar-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2d3a4b;
            text-align: center;
            margin-bottom: 36px;
        }
        .nav {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .nav a {
            display: block;
            padding: 12px 32px;
            color: #4a5a6a;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
        }
        .nav a.active, .nav a:hover {
            background: #eaf3ff;
            color: #3478f6;
            border-left: 4px solid #7eb6ff;
        }
        .content {
            flex: 1;
            display: flex;
            align-items: flex-start;
            justify-content: center;
            padding: 48px 32px;
            min-height: 0;
        }
        .container {
            background: #fff;
            padding: 36px 28px 28px 28px;
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
            width: 900px;
            max-width: calc(100vw - 210px - 64px);
            display: flex;
            flex-direction: column;
            min-height: 60vh;
            max-height: 80vh;
        }
        .title {
            font-size: 1.7rem;
            font-weight: 700;
            color: #2d3a4b;
            margin-bottom: 24px;
            text-align: center;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 18px;
        }
        th, td {
            padding: 12px 8px;
            border-bottom: 1px solid #e3e8ee;
            text-align: center;
        }
        th {
            background: #f5f8fa;
            color: #4a5a6a;
            font-weight: 700;
        }
        .actions button {
            margin: 0 4px;
            padding: 6px 14px;
            border: none;
            border-radius: 6px;
            font-size: 0.98rem;
            cursor: pointer;
            color: #fff;
            background: #7eb6ff;
            transition: background 0.2s;
        }
        .actions button.edit { background: #5eaefd; }
        .actions button.delete { background: #ff6b6b; }
        .actions button.toggle { background: #6dd47e; }
        .actions button:hover { opacity: 0.85; }
        .add-btn {
            display: inline-block;
            background: linear-gradient(90deg, #7eb6ff 0%, #5eaefd 100%);
            color: #fff;
            font-weight: 700;
            border-radius: 8px;
            padding: 10px 24px;
            font-size: 1.05rem;
            text-decoration: none;
            margin-bottom: 18px;
            transition: background 0.2s;
        }
        .add-btn:hover {
            background: linear-gradient(90deg, #5eaefd 0%, #7eb6ff 100%);
        }
        .pagination-bar {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 8px;
            margin-top: 12px;
            font-size: 1rem;
        }
        .page-btn {
            background: #eaf3ff;
            color: #3478f6;
            border: none;
            border-radius: 6px;
            padding: 6px 16px;
            font-size: 1rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .page-btn:disabled {
            background: #f5f8fa;
            color: #b0b8c9;
            cursor: not-allowed;
        }
        .page-size-select {
            padding: 4px 10px;
            border-radius: 6px;
            border: 1px solid #d1d9e6;
            font-size: 1rem;
            outline: none;
        }
        .table-scroll {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
        }
        .logout-btn {
            margin: 32px 24px 0 24px;
            padding: 12px 0;
            width: calc(100% - 48px);
            background: linear-gradient(90deg, #ff6b6b 0%, #ffb36b 100%);
            color: #fff;
            font-weight: 700;
            border: none;
            border-radius: 8px;
            font-size: 1.08rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .logout-btn:hover {
            background: linear-gradient(90deg, #ffb36b 0%, #ff6b6b 100%);
        }
        .book-title-cell {
            max-width: 160px;
            min-width: 80px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .book-title-text {
            display: inline-block;
            max-width: 100%;
            vertical-align: middle;
            white-space: inherit;
            overflow: inherit;
            text-overflow: inherit;
        }
    </style>
</head>
<body>
    <div class="layout">
        <aside class="sidebar">
            <div class="sidebar-title">商家中心</div>
            <nav class="nav">
                <a href="merchant_home.html">首页</a>
                <a href="merchant_books.html" class="active">书籍管理</a>
                <a href="merchant_orders.html">订单处理</a>
                <a href="merchant_add_book.html">发布新书</a>
                <a href="merchant_profile.html">个人信息</a>
            </nav>
            <button id="logoutBtn" class="logout-btn">退出登录</button>
        </aside>
        <main class="content">
            <div class="container">
                <div class="title">书籍管理</div>
                <div class="search-bar">
                    <div class="search-bar-left">
                        <a href="merchant_add_book.html" class="add-btn">+ 发布新书</a>
                    </div>
                    <div class="search-bar-right">
                        <input type="text" id="searchInput" placeholder="搜索书名..." class="search-input">
                        <button id="searchBtn" class="search-btn">搜索</button>
                        <button id="resetBtn" class="reset-btn">重置</button>
                    </div>
                </div>
                <div class="table-scroll">
                <table id="bookTable">
                    <thead>
                        <tr>
                            <th>书籍ID</th>
                            <th>书名</th>
                            <th>作者</th>
                            <th>价格</th>
                            <th>库存</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="bookTableBody">
                        <!-- 数据由JS渲染 -->
                    </tbody>
                </table>
                </div>
                <div class="pagination-bar">
                    <button id="prevPage" class="page-btn">上一页</button>
                    <span id="pageInfo"></span>
                    <button id="nextPage" class="page-btn">下一页</button>
                    <span style="margin-left:24px;">每页显示</span>
                    <select id="pageSizeSelect" class="page-size-select">
                        <option value="5">5</option>
                        <option value="10">10</option>
                        <option value="15">15</option>
                        <option value="20">20</option>
                    </select>
                    <span>条</span>
                </div>
                <script>
                import("./api_config.js").then(({ API_BASE_URL }) => {
                    let currentPage = 1;
                    let pageSize = 5;
                    let total = 0;
                    let totalPages = 0;
                    let searchKeyword = '';
                    
                    // 获取商家ID
                    function getMerchantId() {
                        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                        return userInfo.userId;
                    }
                    
                    // PUT请求
                    async function updateBook(data) {
                        try {
                            const response = await fetch(`${API_BASE_URL}/book`, {
                                method: 'PUT',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(data)
                            });
                            const result = await response.json();
                            if (result.success) {
                                alert('操作成功！');
                                loadBooks();
                            } else {
                                alert(result.message || '操作失败');
                            }
                        } catch (err) {
                            alert('网络错误或服务器无响应');
                        }
                    }
                    
                    // 编辑书籍
                    function editBook(book) {
                        window.showEditModal(book);
                    }
                    
                    // 上下架
                    function toggleBookStatus(book) {
                        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                        const merchantId = userInfo.userId;
                        if (!merchantId) {
                            alert('未检测到商家身份，请重新登录');
                            window.location.href = 'login.html';
                            return;
                        }
                        const data = {
                            id: book.id,
                            merchantId,
                            title: book.title,
                            author: book.author,
                            price: book.price,
                            stock: book.stock,
                            status: book.status === 1 ? 0 : 1
                        };
                        updateBook(data);
                    }
                    
                    // 加载书籍数据
                    async function loadBooks() {
                        const merchantId = getMerchantId();
                        if (!merchantId) {
                            alert('未检测到商家身份，请重新登录');
                            window.location.href = 'login.html';
                            return;
                        }
                        
                        try {
                            const url = `${API_BASE_URL}/book/page?pageNum=${currentPage}&pageSize=${pageSize}&merchantId=${merchantId}&bookName=${encodeURIComponent(searchKeyword)}`;
                            const response = await fetch(url);
                            const result = await response.json();
                            
                            if (result.success) {
                                const data = result.data;
                                renderTable(data.records);
                                total = data.total;
                                totalPages = data.pages;
                                updatePagination();
                            } else {
                                alert(result.message || '获取书籍列表失败');
                            }
                        } catch (err) {
                            alert('网络错误或服务器无响应');
                        }
                    }
                    
                    // 渲染表格
                    function renderTable(books) {
                        const tbody = document.getElementById('bookTableBody');
                        tbody.innerHTML = books.map((b, idx) => `
                            <tr data-idx="${idx}">
                                <td>${b.id}</td>
                                <td class="book-title-cell" title="${b.title}"><span class="book-title-text">${b.title}</span></td>
                                <td>${b.author}</td>
                                <td>￥${b.price}</td>
                                <td>${b.stock}</td>
                                <td>${b.status === 1 ? '上架' : '下架'}</td>
                                <td class="actions">
                                    <button class="edit">编辑</button>
                                    <button class="delete">删除</button>
                                    <button class="toggle">${b.status === 1 ? '下架' : '上架'}</button>
                                </td>
                            </tr>
                        `).join('');
                        // 绑定事件
                        Array.from(document.querySelectorAll('.edit')).forEach((btn, i) => {
                            btn.onclick = function() { editBook(books[i]); };
                        });
                        Array.from(document.querySelectorAll('.delete')).forEach((btn, i) => {
                            btn.onclick = function() {
                                if (!confirm(`确定要删除《${books[i].title}》吗？`)) return;
                                const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                                const merchantId = userInfo.userId;
                                if (!merchantId) {
                                    alert('未检测到商家身份，请重新登录');
                                    window.location.href = 'login.html';
                                    return;
                                }
                                fetch(`${API_BASE_URL}/book/${books[i].id}`, {
                                    method: 'DELETE',
                                    headers: { 'Content-Type': 'application/json' }
                                })
                                .then(response => response.json())
                                .then(result => {
                                    if (result.success) {
                                        alert('删除成功！');
                                        loadBooks();
                                    } else {
                                        alert(result.message || '删除失败');
                                    }
                                })
                                .catch(() => {
                                    alert('网络错误或服务器无响应');
                                });
                            };
                        });
                        Array.from(document.querySelectorAll('.toggle')).forEach((btn, i) => {
                            btn.onclick = function() { toggleBookStatus(books[i]); };
                        });
                    }
                    
                    // 更新分页信息
                    function updatePagination() {
                        document.getElementById('pageInfo').textContent = `第 ${currentPage} / ${totalPages} 页`;
                        document.getElementById('prevPage').disabled = currentPage === 1;
                        document.getElementById('nextPage').disabled = currentPage === totalPages;
                    }
                    
                    // 事件监听
                    document.getElementById('prevPage').onclick = function() {
                        if (currentPage > 1) {
                            currentPage--;
                            loadBooks();
                        }
                    };
                    
                    document.getElementById('nextPage').onclick = function() {
                        if (currentPage < totalPages) {
                            currentPage++;
                            loadBooks();
                        }
                    };
                    
                    document.getElementById('pageSizeSelect').onchange = function() {
                        pageSize = parseInt(this.value);
                        currentPage = 1;
                        loadBooks();
                    };
                    
                    document.getElementById('searchBtn').onclick = function() {
                        searchKeyword = document.getElementById('searchInput').value.trim();
                        currentPage = 1;
                        loadBooks();
                    };
                    
                    document.getElementById('resetBtn').onclick = function() {
                        document.getElementById('searchInput').value = '';
                        searchKeyword = '';
                        currentPage = 1;
                        loadBooks();
                    };
                    
                    // 回车搜索
                    document.getElementById('searchInput').onkeypress = function(e) {
                        if (e.key === 'Enter') {
                            document.getElementById('searchBtn').click();
                        }
                    };
                    
                    // 默认选中5
                    document.getElementById('pageSizeSelect').value = '5';
                    // 初始加载
                    loadBooks();
                    // 每30秒自动刷新书籍数据
                    var bookAutoRefreshTimer = setInterval(loadBooks, 30000);
                    // 页面卸载时清理定时器
                    window.addEventListener('beforeunload', function() { clearInterval(bookAutoRefreshTimer); });
                    // 编辑弹窗交互（作用域内）
                    const modal = document.getElementById('editModal');
                    const form = document.getElementById('editForm');
                    const cancelBtn = form.querySelector('.modal-cancel');
                    let currentBook = null;
                    window.showEditModal = function(book) {
                        currentBook = book;
                        document.getElementById('editId').value = book.id;
                        document.getElementById('editTitle').value = book.title;
                        document.getElementById('editAuthor').value = book.author;
                        document.getElementById('editPrice').value = book.price;
                        document.getElementById('editStock').value = book.stock;
                        modal.style.display = 'flex';
                    };
                    function closeModal() {
                        modal.style.display = 'none';
                        currentBook = null;
                    }
                    cancelBtn.onclick = closeModal;
                    modal.onclick = function(e) { if (e.target === modal) closeModal(); };
                    form.onsubmit = function(e) {
                        e.preventDefault();
                        if (!currentBook) return;
                        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
                        const merchantId = userInfo.userId;
                        if (!merchantId) {
                            alert('未检测到商家身份，请重新登录');
                            window.location.href = 'login.html';
                            return;
                        }
                        const data = {
                            id: currentBook.id,
                            merchantId,
                            title: document.getElementById('editTitle').value.trim(),
                            author: document.getElementById('editAuthor').value.trim(),
                            price: parseFloat(document.getElementById('editPrice').value),
                            stock: parseInt(document.getElementById('editStock').value),
                            status: currentBook.status
                        };
                        updateBook(data);
                        closeModal();
                    };
                    document.getElementById('logoutBtn').onclick = function() {
                        localStorage.removeItem('userInfo');
                        window.location.href = 'login.html';
                    };
                });
                </script>
                <style>
                .search-bar {
                    display: flex;
                    gap: 12px;
                    margin-bottom: 18px;
                    align-items: center;
                    justify-content: space-between;
                }
                .search-bar-left {
                    flex-shrink: 0;
                }
                .search-bar-right {
                    display: flex;
                    gap: 12px;
                    align-items: center;
                }
                .search-input,
                .search-btn,
                .reset-btn,
                .add-btn {
                    height: 40px;
                    line-height: 40px;
                    box-sizing: border-box;
                    font-size: 1rem;
                    font-family: inherit;
                    border-radius: 8px;
                    border-width: 2px;
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    padding-top: 0;
                    padding-bottom: 0;
                }
                .add-btn {
                    padding: 0 20px;
                    border: 2px solid #20c997;
                    margin-bottom: 0;
                }
                .search-input {
                    width: 320px;
                    min-width: 0;
                    max-width: 100%;
                    flex: none;
                    padding: 10px 12px;
                    border: 1px solid #d1d9e6;
                    border-radius: 8px;
                    font-size: 1rem;
                    outline: none;
                    transition: border 0.2s;
                }
                .search-input:focus {
                    border-color: #7eb6ff;
                }
                .search-btn {
                    background: linear-gradient(90deg, #7eb6ff 0%, #5eaefd 100%);
                    color: #fff;
                    font-weight: 700;
                    border: none;
                    border-radius: 8px;
                    padding: 10px 20px;
                    font-size: 1rem;
                    cursor: pointer;
                    transition: background 0.2s;
                }
                .search-btn:hover {
                    background: linear-gradient(90deg, #5eaefd 0%, #7eb6ff 100%);
                }
                .reset-btn {
                    background: linear-gradient(90deg, #6c757d 0%, #5a6268 100%);
                    color: #fff;
                    font-weight: 700;
                    border: none;
                    border-radius: 8px;
                    padding: 10px 20px;
                    font-size: 1rem;
                    cursor: pointer;
                    transition: background 0.2s;
                }
                .reset-btn:hover {
                    background: linear-gradient(90deg, #5a6268 0%, #6c757d 100%);
                }
                .add-btn {
                    display: inline-block;
                    background: #fff;
                    color: #20c997;
                    font-weight: 700;
                    border-radius: 8px;
                    border: 2px solid #20c997;
                    padding: 10px 20px;
                    font-size: 1rem;
                    text-decoration: none;
                    transition: background 0.2s, color 0.2s;
                    height: 40px;
                    line-height: 20px;
                    box-sizing: border-box;
                }
                .add-btn:hover {
                    background: #20c997;
                    color: #fff;
                }
                </style>
            </div>
        </main>
    </div>
    <!-- 编辑书籍弹窗 -->
    <div id="editModal" class="modal" style="display:none;">
      <div class="modal-content">
        <div class="modal-title">编辑书籍</div>
        <form id="editForm">
          <input type="hidden" id="editId">
          <div class="modal-row">
            <label>书名</label>
            <input type="text" id="editTitle" required maxlength="50">
          </div>
          <div class="modal-row">
            <label>作者</label>
            <input type="text" id="editAuthor" required maxlength="30">
          </div>
          <div class="modal-row">
            <label>价格</label>
            <input type="number" id="editPrice" required min="0" step="0.01">
          </div>
          <div class="modal-row">
            <label>库存</label>
            <input type="number" id="editStock" required min="0" step="1">
          </div>
          <div class="modal-actions">
            <button type="submit" class="modal-confirm">保存</button>
            <button type="button" class="modal-cancel">取消</button>
          </div>
        </form>
      </div>
    </div>
    <style>
    .modal {
      position: fixed;
      left: 0; top: 0; right: 0; bottom: 0;
      background: rgba(0,0,0,0.18);
      z-index: 9999;
      display: flex;
      align-items: center;
      justify-content: center;
      animation: fadeIn 0.2s;
    }
    @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
    .modal-content {
      background: #fff;
      border-radius: 14px;
      box-shadow: 0 8px 32px rgba(0,0,0,0.18);
      padding: 32px 32px 18px 32px;
      min-width: 340px;
      max-width: 96vw;
      min-height: 0;
      display: flex;
      flex-direction: column;
      gap: 12px;
      position: relative;
      animation: popIn 0.2s;
    }
    @keyframes popIn { from { transform: scale(0.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
    .modal-title {
      font-size: 1.25rem;
      font-weight: 700;
      color: #2d3a4b;
      margin-bottom: 10px;
      text-align: center;
    }
    .modal-row {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 10px;
    }
    .modal-row label {
      width: 56px;
      color: #4a5a6a;
      font-size: 1rem;
      text-align: right;
    }
    .modal-row input {
      flex: 1;
      padding: 8px 10px;
      border-radius: 6px;
      border: 1px solid #d1d9e6;
      font-size: 1rem;
      outline: none;
      transition: border 0.2s;
    }
    .modal-row input:focus {
      border-color: #7eb6ff;
    }
    .modal-actions {
      display: flex;
      justify-content: flex-end;
      gap: 16px;
      margin-top: 8px;
    }
    .modal-confirm {
      background: linear-gradient(90deg, #7eb6ff 0%, #5eaefd 100%);
      color: #fff;
      font-weight: 700;
      border: none;
      border-radius: 8px;
      padding: 8px 24px;
      font-size: 1rem;
      cursor: pointer;
      transition: background 0.2s;
    }
    .modal-confirm:hover {
      background: linear-gradient(90deg, #5eaefd 0%, #7eb6ff 100%);
    }
    .modal-cancel {
      background: #f5f8fa;
      color: #4a5a6a;
      font-weight: 700;
      border: none;
      border-radius: 8px;
      padding: 8px 24px;
      font-size: 1rem;
      cursor: pointer;
      transition: background 0.2s;
    }
    .modal-cancel:hover {
      background: #e3e8ee;
    }
    </style>
</body>
</html> 